Matrix multiplication is a mathematical operation that involves multiplying two matrices to produce a new matrix. In order to perform matrix multiplication, the number of columns in the first matrix should be equal to the number of rows in the second matrix.
To perform matrix multiplication in C, use nested loops to traverse through the rows and columns of the matrices and calculate the corresponding elements of the resulting matrix.
#include <stdio.h>
#define ROW_A 2
#define COL_A 3
#define ROW_B 3
#define COL_B 2
void matrixMultiplication(int A[][COL_A], int B[][COL_B], int C[][COL_B]) {
for (int i = 0; i < ROW_A; i++) {
for (int j = 0; j < COL_B; j++) {
C[i][j] = 0;
for (int k = 0; k < COL_A; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
void displayMatrix(int mat[][COL_B], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
int main() {
int matrixA[ROW_A][COL_A] = {{1, 2, 3}, {4, 5, 6}};
int matrixB[ROW_B][COL_B] = {{7, 8}, {9, 10}, {11, 12}};
int resultMatrix[ROW_A][COL_B];
// Perform matrix multiplication
matrixMultiplication(matrixA, matrixB, resultMatrix);
printf("Matrix A:\n");
displayMatrix(matrixA, ROW_A, COL_A);
printf("Matrix B:\n");
displayMatrix(matrixB, ROW_B, COL_B);
printf("Resultant Matrix (A * B):\n");
displayMatrix(resultMatrix, ROW_A, COL_B);
return 0;
}
Matrix A:
1 2 3
4 5 6
Matrix B:
7 8
9 10
11 12
Resultant Matrix (A * B):
58 64
139 154
What is the result of multiplying two matrices together in C?
What is the operation used for matrix multiplication in C?
What is the time complexity of matrix multiplication in C?